package com.jerry.frame.netty.demo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

public class EchoServer {

    private int port;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public EchoServer(int  port ) {

        this.port = port;
    }

    public void start() throws Exception {
        NioEventLoopGroup group = new NioEventLoopGroup(); //3
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(group)                                //设置接收和处理的线程组
                    .channel(NioServerSocketChannel.class)        //设置通道类型
                    .localAddress(new InetSocketAddress(port))    //设置地址
                    .childHandler(new ChannelInitializer<SocketChannel>() { //设置每一个通道建立绑定handler的初始化类
                        @Override
                        public void initChannel(SocketChannel ch)
                                throws Exception {
                            ch.pipeline().addLast(
                                    new EchoServerHandler());
                        }
                    });

            ChannelFuture f = b.bind().sync();            //等待服务绑定完成
            System.out.println(EchoServer.class.getName() + " started and listen on " + f.channel().localAddress());
            f.channel().closeFuture().sync();            //等待服务关闭
        } finally {
            group.shutdownGracefully().sync();            //10
        }


}

    public static void main(String[] args) throws Exception {

        new EchoServer(1000).start();                //2
    }
}
